//
//  ByChartBaseView.m
//  laserdevice_ios
//
//  Created by pro on 16/11/28.
//  Copyright © 2016年 com.itboye. All rights reserved.
//

#import "ByChartBaseView.h"

// view
#import "ByChartLayerView.h"    

@implementation ByChartBaseView
{
    // view
    ByChartLayerView *_lineView;        // 折线视图

    ByChartLayerView *_axisView;        // 坐标轴视图
    ByChartLayerView *_metricView;      // 度量视图（与x轴平行的虚线）

    UIView           *_xAxisLabels;     // x轴坐标视图
    UIView           *_yAxisLabels;     // y轴坐标视图
    
    UILabel          *_maxValueLabel;   // 最大值
    UILabel          *_minValueLabel;   // 最小值
    UILabel          *_avgValueLabel;   // 平均值

    // data
    CGFloat          _maxValue;         // 最大值
    CGFloat          _minValue;         // 最小值
    CGFloat          _avgValue;         // 平均值
    CGFloat          _maxAxisOfY;       // y轴最大值

}



static CGFloat      const kAdjustViewHeight     = 40;
static CGFloat      const kAxisLeft             = 40;
static CGFloat      const kAxisRight            = 10;
static CGFloat      const kAxisTop              = 10;
static CGFloat      const kAxisbottom           = 20 + kAdjustViewHeight;
static NSInteger    const kAxisCountOfY         = 20;
static NSInteger    const kAxisCountOfX         = 10;

- (instancetype)initWithFrame:(CGRect)frame {
    
    if (self = [super initWithFrame:frame]) {
        
        self.backgroundColor = [UIColor whiteColor];
        
        _maxAxisOfY = 1;
        _measureValues = @[];
        _maxAmountOfX = 100;
        
        [self setLineView];
        [self setupAxisView];
        [self setupMetricView];
        [self setupXAxisLabels];
        [self setupYAxisLabels];
        [self setupValueReportView];
        [self setupAdjustView];
        [self setUnitLabel];
    }
    return self;
}

#pragma mark - 辅助
- (NSString *)transferUnitWithData:(CGFloat)data {
    
    int unit = [ByCommonCache getSystemUnit].intValue;
    switch (unit) {
        case 0: // 米
            return [NSString stringWithFormat:@"%.3f", data];
            break;
        case 1: // 英尺
            return [NSString stringWithFormat:@"%.3f", data * 3.2808399];
            break;
        case 2: // 英寸
            return [NSString stringWithFormat:@"%.2f", data * 3.2808399 * 12];
            break;
        case 3: // 英尺+英寸
            return [NSString stringWithFormat:@"%.0f\'%.2f\"", floorf(data * 3.2808399), ((data * 3.2808399) - floorf(data * 3.2808399)) * 12.000];
            break;
        default:
            break;
    }
    
    return nil;
}

#pragma mark - 外部实现
- (void)setTotalMeasureValues:(NSArray *)totalMeasureValues {
    
    _totalMeasureValues = totalMeasureValues;
    
    // 最大超过1000，则只使用最新的1000个数据
    if (_totalMeasureValues.count > 1000) {
        NSMutableArray *temp = [[NSMutableArray alloc] initWithArray:_totalMeasureValues];
        _totalMeasureValues = [temp subarrayWithRange:NSMakeRange(_totalMeasureValues.count - 1000, 1000)];
    }
    
    _maxValue = 0;
    _minValue = HUGE_VALF;
    _avgValue = 0;
    
    // 遍历获得最大值和最小值
    for (NSNumber *number in _totalMeasureValues) {
        CGFloat valyeY = [number floatValue];
        if (valyeY > _maxValue) {
            _maxValue = valyeY;
        }
        if (valyeY < _minValue) {
            _minValue = valyeY;
        }
    }
    
    _maxAxisOfY = _maxValue * 1.1;
    
    
    
    // 根据实际数据的个数和最大需要展示的数据个数来设置需要展示的数据数组
    if (_totalMeasureValues.count > _maxAmountOfX) {
        NSMutableArray *temp = [[NSMutableArray alloc] initWithArray:_totalMeasureValues];
        self.measureValues = [temp subarrayWithRange:NSMakeRange(_totalMeasureValues.count - _maxAmountOfX - 1, _maxAmountOfX + 1)];
    } else {
        self.measureValues = [_totalMeasureValues copy];
    }
    
    // 遍历获得最大值和最小值
    _maxValue = 0;
    _minValue = HUGE_VALF;
    _avgValue = 0;
    CGFloat total = 0;
    for (NSNumber *number in self.measureValues) {
        CGFloat valyeY = [number floatValue];
        total += valyeY;
        if (valyeY > _maxValue) {
            _maxValue = valyeY;
        }
        if (valyeY < _minValue) {
            _minValue = valyeY;
        }
    }
    // 计算平均值
    _avgValue = total / self.measureValues.count;
    
    if (self.measureValues.count == 0) {
        _avgValue = 0;
    }
    if (_minValue > 1000000) {
        _minValue = 0;
    }
    
    // 设置最大值，最小值，平均值
    _maxValueLabel.text = [self transferUnitWithData:_maxValue];
    _minValueLabel.text = [self transferUnitWithData:_minValue];
    _avgValueLabel.text = [self transferUnitWithData:_avgValue];

    
}
// 设置测量数据
- (void)setMeasureValues:(NSArray *)measureValues {
    
    _measureValues = measureValues;
    
    // 设置y轴坐标
    for (int i = 0; i < _yAxisLabels.subviews.count; i ++) {
        UILabel *yLabel = _yAxisLabels.subviews[i];
        yLabel.text = [self transferUnitWithData:_maxAxisOfY / 20 * (20 - i)];
    }
    
    [self redrawLineLayer];
}



// 设置同步调整点个数
- (void)setMaxAmountOfX:(NSInteger)maxAmountOfX {
    
    if (_maxAmountOfX == maxAmountOfX) {
        return;
    }
    _maxAmountOfX = maxAmountOfX;
    [self setTotalMeasureValues:_totalMeasureValues];
    
    // 设置x轴坐标
    for (int i = 0; i < _xAxisLabels.subviews.count; i ++) {
        UILabel *xLabel = _xAxisLabels.subviews[i];
        xLabel.text = [NSString stringWithFormat:@"%li", _maxAmountOfX / kAxisCountOfX * i];
    }
    
    
    
    [self redrawLineLayer];
}
// 重新绘制线条
- (void)redrawLineLayer {
    
    UIBezierPath *linePath = [UIBezierPath bezierPath];
    CGFloat width = _lineView.superview.width;
    CGFloat height = _lineView.superview.height;
    
    if (_measureValues.count == 0) {
        return;
    }
    
    [linePath moveToPoint:CGPointMake(0, (1 - [_measureValues[0] floatValue] / _maxAxisOfY) * height)];
    for (int i = 1; i < _measureValues.count; i ++) {
        
        CGPoint point = CGPointMake(i * width / _maxAmountOfX, (1 - [_measureValues[i] floatValue] / _maxAxisOfY) * height);
        [linePath addLineToPoint:point];
    }
    _lineView.shapeLayer.path = linePath.CGPath;
}

#pragma mark - 创建视图
- (void)setUnitLabel {
    
    CGFloat x = 0;
    CGFloat y = 0;
    CGFloat width = kAxisLeft;
    CGFloat height = 30;
    UILabel *unitLabel = [[UILabel alloc] initWithFrame:CGRectMake(x, y, width, height)];
    unitLabel.adjustsFontSizeToFitWidth = YES;
    unitLabel.font = FONT(14);
    int unit = [ByCommonCache getSystemUnit].intValue;
    switch (unit) {
        case 0: // 米
            unitLabel.text = @"m";
            break;
        case 1: // 英尺
            unitLabel.text = @"ft";
            break;
        case 2: // 英寸
            unitLabel.text = @"in";
            break;
        case 3: // 英尺+英寸
            unitLabel.text = @"ft+in";
            break;
        default:
            break;
    }
    unitLabel.textColor = CJ_THEME_COLOR;
    unitLabel.textAlignment = NSTextAlignmentCenter;
    [self addSubview:unitLabel];
}

- (void)setLineView {
    
    CGFloat x = kAxisLeft;
    CGFloat y = kAxisTop + 30;
    CGFloat width = self.width - kAxisRight - x;
    CGFloat height = self.height - kAxisbottom - y;
    UIView *lineBgView = [[UIView alloc] initWithFrame:CGRectMake(x, y, width, height)];
    [self addSubview:lineBgView];
    
    _lineView = [[ByChartLayerView alloc] init];
    _lineView.shapeLayer.fillColor = nil;
    _lineView.shapeLayer.strokeColor = CJ_THEME_COLOR.CGColor;
    _lineView.backgroundColor = [UIColor clearColor];
    _lineView.opaque = NO;
    [lineBgView addSubview:_lineView];
}
- (void)setupAxisView {
    
    _axisView = [[ByChartLayerView alloc] init];
    _axisView.shapeLayer.fillColor = nil;
    _axisView.shapeLayer.strokeColor = [UIColor blackColor].CGColor;
    _axisView.backgroundColor = [UIColor clearColor];
    _axisView.opaque = NO;
    [self addSubview:_axisView];
    
    UIBezierPath *lineOfAxis = [UIBezierPath bezierPath];
    [lineOfAxis moveToPoint:CGPointMake(kAxisLeft, 10)];
    [lineOfAxis addLineToPoint:CGPointMake(kAxisLeft, self.height - kAxisbottom)];
    [lineOfAxis addLineToPoint:CGPointMake(self.width - kAxisRight, self.height - kAxisbottom)];

    _axisView.shapeLayer.path = lineOfAxis.CGPath;
}
- (void)setupMetricView {
    
    _metricView = [[ByChartLayerView alloc] init];
    _metricView.shapeLayer.fillColor = nil;
    _metricView.shapeLayer.strokeColor = [UIColor colorWithWhite:0.5 alpha:1].CGColor;
    _metricView.shapeLayer.lineWidth = 0.5;
    _metricView.backgroundColor = [UIColor clearColor];
    _metricView.opaque = NO;
    [self addSubview:_metricView];
    
    UIBezierPath *lineOfMetric = [UIBezierPath bezierPath];
    CGFloat beginOfY = kAxisTop + 30;
    CGFloat endOfY = self.height - kAxisbottom;
    CGFloat marginOfY = (endOfY - beginOfY) / kAxisCountOfY;
    for (int i = 0; i < kAxisCountOfY; i ++) {
        [lineOfMetric moveToPoint:CGPointMake(kAxisLeft, beginOfY + marginOfY * i)];
        [lineOfMetric addLineToPoint:CGPointMake(self.width - kAxisRight, beginOfY + marginOfY * i)];
    }
    _metricView.shapeLayer.lineDashPattern = @[@3, @2];
    _metricView.shapeLayer.path = lineOfMetric.CGPath;
    
}

- (void)setupXAxisLabels {
    
    _xAxisLabels = [[UIView alloc] initWithFrame:CGRectMake(0, self.height - kAxisbottom, self.width, 20)];
    [self addSubview:_xAxisLabels];
    
    CGFloat beginOfX = kAxisLeft;
    CGFloat endOfX = self.width - kAxisRight;
    CGFloat marginOfX = (endOfX - beginOfX) / kAxisCountOfX;
    
    for (int i = 0; i <= kAxisCountOfX; i ++) {
        
        CGFloat x = 0;
        CGFloat y = 0;
        CGFloat width = marginOfX;
        CGFloat height = 20;
        UILabel *xLabel = [[UILabel alloc] initWithFrame:CGRectMake(x, y, width, height)];
        xLabel.adjustsFontSizeToFitWidth = YES;
        xLabel.font = FONT(10);
        xLabel.text = [NSString stringWithFormat:@"%li", i * (_maxAmountOfX / kAxisCountOfX)];
        xLabel.textColor = CJ_THEME_COLOR;
        xLabel.textAlignment = NSTextAlignmentCenter;
        [_xAxisLabels addSubview:xLabel];
        
        xLabel.x = beginOfX + marginOfX * i;
    }
    
}
- (void)setupYAxisLabels {
    
    _yAxisLabels = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kAxisLeft, self.height)];
    [self addSubview:_yAxisLabels];
    
    CGFloat beginOfY = kAxisTop + 30;
    CGFloat endOfY = self.height - kAxisbottom;
    CGFloat marginOfY = (endOfY - beginOfY) / kAxisCountOfY;

    for (int i = 0; i <= kAxisCountOfY; i ++) {
        
        CGFloat x = 0;
        CGFloat y = 0;
        CGFloat width = kAxisLeft;
        CGFloat height = marginOfY;
        UILabel *yLabel = [[UILabel alloc] initWithFrame:CGRectMake(x, y, width, height)];
        yLabel.adjustsFontSizeToFitWidth = YES;
        yLabel.font = FONT(10);
        yLabel.text = @"0.00";
        yLabel.textColor = CJ_THEME_COLOR;
        yLabel.textAlignment = NSTextAlignmentCenter;
        [_yAxisLabels addSubview:yLabel];
        
        yLabel.y = beginOfY + i * marginOfY;
    }
}

// 记录数据的视图（最大值，最小值，平均值）
- (void)setupValueReportView {
    
    NSString *maxText = STRING(@"zuidazhi");
    NSString *minText = STRING(@"zuixiaozhi");
    NSString *avgText = STRING(@"pingjunzhi");
    CGFloat x, y, width, height;
    CGFloat margin = 8;
    CGFloat valueLabelWidth = (self.width - kAxisRight - kAxisLeft - 10 - ([maxText getSizeOfString:14].width + [minText getSizeOfString:14].width + [avgText getSizeOfString:14].width) - margin * 2) / 3;
    
    // 1.最大值titleLabel
    x = kAxisLeft + 10;
    y = kAxisTop;
    width = [maxText getSizeOfString:14].width;
    height = 20;
    UILabel *maxTitleLabel = [[UILabel alloc] initWithFrame:CGRectMake(x, y, width, height)];
    maxTitleLabel.adjustsFontSizeToFitWidth = YES;
    maxTitleLabel.font = FONT(14);
    maxTitleLabel.text = maxText;
    maxTitleLabel.textColor = [UIColor darkGrayColor];
    maxTitleLabel.textAlignment = NSTextAlignmentCenter;
    [self addSubview:maxTitleLabel];
    
    // 2.最大值valueLabel
    x = maxTitleLabel.right;
    y = maxTitleLabel.top;
    width = valueLabelWidth;
    height = 20;
    _maxValueLabel = [[UILabel alloc] initWithFrame:CGRectMake(x, y, width, height)];
    _maxValueLabel.font = FONT(14);
    _maxValueLabel.text = @"0.00";
    _maxValueLabel.textAlignment = NSTextAlignmentCenter;
    _maxValueLabel.textColor = CJ_THEME_COLOR;
    [self addSubview:_maxValueLabel];
    _maxValueLabel.layer.borderColor = [UIColor lightGrayColor].CGColor;
    _maxValueLabel.layer.borderWidth = 1;
    
    // 3.最小值titleLabel
    x = _maxValueLabel.right + margin;
    y = kAxisTop;
    width = [minText getSizeOfString:14].width;
    height = 20;
    UILabel *minTitleLabel = [[UILabel alloc] initWithFrame:CGRectMake(x, y, width, height)];
    minTitleLabel.adjustsFontSizeToFitWidth = YES;
    minTitleLabel.font = FONT(14);
    minTitleLabel.text = minText;
    minTitleLabel.textColor = [UIColor darkGrayColor];
    minTitleLabel.textAlignment = NSTextAlignmentCenter;
    [self addSubview:minTitleLabel];
    
    // 4.最小值valueLabel
    x = minTitleLabel.right;
    y = minTitleLabel.top;
    width = valueLabelWidth;
    height = 20;
    _minValueLabel = [[UILabel alloc] initWithFrame:CGRectMake(x, y, width, height)];
    _minValueLabel.font = FONT(14);
    _minValueLabel.text = @"0.00";
    _minValueLabel.textAlignment = NSTextAlignmentCenter;
    _minValueLabel.textColor = CJ_THEME_COLOR;
    [self addSubview:_minValueLabel];
    _minValueLabel.layer.borderColor = [UIColor lightGrayColor].CGColor;
    _minValueLabel.layer.borderWidth = 1;
    
    // 5.平均值titleLabel
    x = _minValueLabel.right + margin;
    y = kAxisTop;
    width = [avgText getSizeOfString:14].width;
    height = 20;
    UILabel *avgTitleLabel = [[UILabel alloc] initWithFrame:CGRectMake(x, y, width, height)];
    avgTitleLabel.adjustsFontSizeToFitWidth = YES;
    avgTitleLabel.font = FONT(14);
    avgTitleLabel.text = avgText;
    avgTitleLabel.textColor = [UIColor darkGrayColor];
    avgTitleLabel.textAlignment = NSTextAlignmentLeft;
    [self addSubview:avgTitleLabel];
    
    // 6.平均值valueLabel
    x = avgTitleLabel.right;
    y = avgTitleLabel.top;
    width = valueLabelWidth;
    height = 20;
    _avgValueLabel = [[UILabel alloc] initWithFrame:CGRectMake(x, y, width, height)];
    _avgValueLabel.font = FONT(14);
    _avgValueLabel.text = @"0.00";
    _avgValueLabel.textAlignment = NSTextAlignmentCenter;
    _avgValueLabel.textColor = CJ_THEME_COLOR;
    [self addSubview:_avgValueLabel];
    _avgValueLabel.layer.borderColor = [UIColor lightGrayColor].CGColor;
    _avgValueLabel.layer.borderWidth = 1;
}


- (void)setupAdjustView {
    
    UIView *adjustView = [[UIView alloc] initWithFrame:CGRectMake(0, self.height - kAdjustViewHeight, self.width, kAdjustViewHeight)];
    adjustView.backgroundColor = rgba(3, 41, 84, 1);
    [self addSubview:adjustView];
    
    NSString *text = STRING(@"tongbutiaozhengdian");
    UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 0, [text getSizeOfString:14].width + 10, adjustView.height)];
    titleLabel.adjustsFontSizeToFitWidth = YES;
    titleLabel.font = FONT(14);
    titleLabel.text = text;
    titleLabel.textColor = [UIColor whiteColor];
    titleLabel.textAlignment = NSTextAlignmentLeft;
    [adjustView addSubview:titleLabel];
    
    UISlider *slider = [[UISlider alloc] initWithFrame:CGRectMake(titleLabel.right, 10, self.width - 10 - titleLabel.right, 20)];
    [slider addTarget:self action:@selector(sliderDidChangeValue:) forControlEvents:UIControlEventValueChanged];
    slider.value = 0.5;
    
    [slider setThumbImage:[UIImage imageNamed:@"real-time_fangkuai"] forState:UIControlStateNormal]; 
    [adjustView addSubview:slider];
}


- (void)sliderDidChangeValue:(UISlider *)sender {
    
    NSLog(@"%lf", sender.value);
    
    // 区间在10-100
    NSInteger amount = 0;
    if (sender.value <= 0.5) {
        amount = 10 + (sender.value) / 0.5 * (100 - 10);
        amount -= (amount % 10);
    }
    // 区间在100-1000
    else {
        amount = 100 + (sender.value - 0.5) / 0.5 * (1000 - 100);
        amount -= (amount % 10);
    }
    
    self.maxAmountOfX = amount;
}

@end
